package com.dayuanit.dy15.atm.handler;

import com.alibaba.fastjson.JSON;
import com.dayuanit.dy15.atm.dto.WebSocketMessageDTO;
import com.dayuanit.dy15.atm.entity.WebSocketMessage;
import com.dayuanit.dy15.atm.service.MessageService;
import com.dayuanit.dy15.atm.util.ApiConnector;
import com.dayuanit.dy15.atm.util.MoneyUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class WebSocketHandler {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);

    private static final String transfer_message_format = "您有一笔转账金额%s元已到账";

    @Value("${websocket.send.message.url}")
    private String websocketUrl;

    @Autowired
    private MessageService messageService;

    public void sendTransferMessage(int amount, long userId) {
        try {
            String renminbi = MoneyUtil.fenToYuan(amount);
            String message = String.format(transfer_message_format, renminbi);

            //先保存到数据库
            WebSocketMessageDTO webSocketMessageDTO = messageService.saveMessage(1, message, userId, renminbi);

            //发送消息给转入方  调用消息中心的接口
            List<NameValuePair> params = new ArrayList<>(2);
            params.add(new BasicNameValuePair("userId", String.valueOf(userId)));
            params.add(new BasicNameValuePair("message", JSON.toJSONString(webSocketMessageDTO)));

            String resultMsg = ApiConnector.post(websocketUrl, params);
            logger.info(">>>>>>>>>消息中心返回:{}", resultMsg);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

    }
}
